package com.zhangsun.yueBoot.admin.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangsun.yueBoot.admin.user.entity.User;
import com.zhangsun.yueBoot.admin.user.mapper.UserMapper;
import com.zhangsun.yueBoot.commons.base.bean.TheUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户登陆信息service实现
 */
@Service("theUserDetailsService")
public class TheUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 构建用户信息的逻辑
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no", username);
        wrapper.ne("status", 9);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("该账号不存在");
        }

        TheUserDetails userInfo = new TheUserDetails();
        userInfo.setUsername(user.getUserNo());
        userInfo.setPassword(user.getPassword());
        userInfo.setUserId(user.getId());
        userInfo.setName(user.getUserName());
        userInfo.setIcon(user.getIcon());
        userInfo.setAccountNonLocked(user.getStatus() == 0);

        Set<GrantedAuthority> authoritiesSet = new HashSet<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;
    }
}
